package com.bybops.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import baseproject.com.mybaseproject.mvp.contract.NewDeviceInitFragmentContract
import baseproject.com.mybaseproject.ui.base.BaseMVPFragment
import baseproject.com.mybaseproject.utils.ActivityUtils
import baseproject.com.mybaseproject.utils.scheduler.RxUtils
import com.bybops.R
import com.bybops.app.MyApplication
import com.bybops.model.api.URLConstant
import com.bybops.model.bean.LockDetail
import com.bybops.presenter.NewDeviceInitFragmentPresenterImpl
import com.bybops.ui.activity.NewDeviceUseActivity
import com.bybops.ui.activity.ScanActivity
import com.uuzuche.lib_zxing.activity.CodeUtils
import kotlinx.android.synthetic.main.fragment_new_device_init.*

/**
 * 新设备启用的初始化界面
 */
class NewDeviceInitFragment : BaseMVPFragment<NewDeviceInitFragmentContract.View, NewDeviceInitFragmentPresenterImpl>()
        , NewDeviceInitFragmentContract.View {


    override var mPresenter: NewDeviceInitFragmentPresenterImpl = NewDeviceInitFragmentPresenterImpl()
    var mActivity: NewDeviceUseActivity? = null



    private val Result_deviceId = 10
    private val Result_lockId = 20
    override fun getLayoutId(): Int? {
        return R.layout.fragment_new_device_init
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mActivity = (activity as NewDeviceUseActivity)
        initView()
        addListener()
    }

    private fun initView() {
        //责任人默认为自己
        tvDutyMan.text = MyApplication.instance?.mUser?.userName
    }

    /**
     * 监听事件
     */
    private fun addListener() {
        //设备id
        RxUtils.rxClick(llDeviceId, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                activity?.let { ActivityUtils.startActivityForResult(it, ScanActivity::class.java, Result_deviceId) }
            }
        })
        //蓝牙锁id
        RxUtils.rxClick(llLockId, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                activity?.let { ActivityUtils.startActivityForResult(it, ScanActivity::class.java, Result_lockId) }
            }
        })
        //初始化按钮
        RxUtils.rxClick(initButton, object : RxUtils.OnClickInterf {
            override fun onViewClick(view: View) {
                //判空处理
                when {
                    TextUtils.isEmpty(tvDeviceId.text.toString().trim()) -> {
                        showToast("设备ID为空")
                        return
                    }
                    TextUtils.isEmpty(tvLockId.text.toString().trim()) -> {
                        showToast("蓝牙锁ID为空")
                        return
                    }
                    TextUtils.isEmpty(etHospital.text.toString().trim()) -> {
                        showToast("医院为空")
                        return
                    }
                    TextUtils.isEmpty(etAddress.text.toString().trim()) -> {
                        showToast("位置为空")
                        return
                    }
                    TextUtils.isEmpty(tvDutyMan.text.toString().trim()) -> {
                        showToast("责任人为空")
                        return
                    }
                    //暂存参数
                    else -> {
                        mActivity?.mDeviceId = tvDeviceId.text.toString().trim()
                        mActivity?.mLockId = tvLockId.text.toString().trim()
                        mActivity?.mHospital = etHospital.text.toString().trim()
                        mActivity?.mAddress = etAddress.text.toString().trim()
                        mActivity?.mDailyMan = tvDutyMan.text.toString().trim()
                        //根据蓝牙锁id获取mac地址
                        mPresenter.getDetailByBarCode()
                    }
                }
            }
        })
    }
    //获取到蓝牙锁的电量
    override fun setLockVoltage(voltage: String?) {
        mActivity?.mVoltage = voltage
        //调用启用新设备接口
        var params = HashMap<String, String?>()
        params["type"] = "1"
        params["equipSN"] = tvLockId.text.toString().trim()
        params["access_token"] = MyApplication.instance?.mAccessToken
        params["barcode"] = tvDeviceId.text.toString().trim()
        params["energy"] = voltage
        params["userKey"] = MyApplication.instance?.mUser?.userKey
        params["userName"] = tvDutyMan.text.toString().trim()
        params["hospital"] = etHospital.text.toString().trim()
        params["hospitalId"] = ""
        params["department"] = etAddress.text.toString().trim()
        mPresenter.activeDevice(params)
    }

    /**
     * 根据蓝牙锁id获取mac地址成功
     */
    override fun getDetailByBarCodeSuccess(data: LockDetail) {
        //读取蓝牙锁信息
        mActivity?.lockName = data.lockName
    }

    /**
     * 初始化接口访问成功
     */
    override fun onActiveDeviceSuccess(data: LockDetail) {
        mActivity?.step(1)
    }

    override fun getDviceId(): String? {
        return tvDeviceId.text.toString().trim()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //处理扫描结果（在界面上显示）
        if (null != data) {
            if (data.extras != null) {
                if (data.extras.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    var result = data.extras.getString(CodeUtils.RESULT_STRING)
                    if (requestCode == Result_deviceId) {
                        //设备ID
                        //截取
                        if (result.startsWith(URLConstant.mPrefix_RQCode)) {
                            var deviceId = result.substring(result.lastIndexOf("/") + 1, result.length)
                            tvDeviceId.text = deviceId
                        }else{
                            showToast("扫描错误二维码")
                        }

                    } else if (requestCode == Result_lockId) {
                        //蓝牙锁id
                        if (result.startsWith("UN")) {
                            tvLockId.text = result
                        }else{
                            showToast("扫描错误二维码")
                        }
                    }
                } else {
                    showToast("解析二维码失败")
                }
            } else {
                return
            }
        }
    }
}